import { login } from "@/api/index";
import { setItem, getItem, removeAllItem } from "@/utils/storage";
import router from "@/router";
import { setTimeStamp } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => ({
    token: getItem("token") || "",
    userInfo: getItem("userInfo") || {},
  }),
  mutations: {
    // 设置token
    setToken(state, token) {
      state.token = token;
      setItem("token", token);
    },
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
      setItem("userInfo", userInfo);
    },
  },
  actions: {
    // 登录动作
    login(context, userInfo) {
      const { account, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({
          account,
          password,
        }).then((data) => {
          // console.log(data);
          let userInfo = data.data;
          userInfo.type = data.type;
          this.commit("user/setUserInfo", userInfo);
          this.commit("user/setToken", data.token);
          router.push("/");
          setTimeStamp()
          resolve();
        });
      });
    },

    // 退出动作
    logout() {
      this.commit("user/setToken", "");
      this.commit("user/setUserInfo", {});
      removeAllItem();
      router.push("/login");
    },
  },
};
